<template>
  <div class="view-api">
    <div class="view-head">
      <div class="head-start">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item
            v-for="(item,i) in paths"
            :key="i + item.text">
            <span class="path-item">
              <span class="path-text">{{ item.text }}</span>
              <i v-if="i + 1 === paths.length" @click="handleShowRename" class="el-icon-edit path-edit"></i>
            </span>
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="head-center"></div>
      <div class="head-end">
        <el-button size="mini" icon="el-icon-postcard">保存</el-button>
        <el-select v-model="form.env" placeholder="请选择环境" size="mini" clearable>
          <el-option
            v-for="item in envList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-button @click="handleShowSetting" size="mini" icon="el-icon-setting">设置</el-button>
        <el-dropdown size="small">
          <el-button size="mini">
            更多<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="handleShowRename">重命名</el-dropdown-item>
            <el-dropdown-item>
              <FileGet @change="handleImport($event)" accept="application/json">导入</FileGet>
            </el-dropdown-item>
            <el-dropdown-item @click.native="handleShowExport">导出</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
    <div class="view-body">
      <el-tabs v-model="activeTab">
        <el-tab-pane :label="tabs[0].text" name="first">
          <InterfaceView v-model="value" />
        </el-tab-pane>
        <el-tab-pane :label="tabs[1].text" name="second">
          <InterfaceView v-model="value" />
        </el-tab-pane>
        <el-tab-pane :label="tabs[2].text" name="third">
          <InterfaceView v-model="value" />
        </el-tab-pane>
      </el-tabs>
    </div>
    <el-dialog
      title="重命名"
      :visible.sync="renameVisible"
      width="480px"
      custom-class="dialog-export">
      <el-form label-width="80px" class="form-export">
        <el-form-item label="名称">
          <el-input v-model="formRename.name" placeholder="请输入名称"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleConfirmRename">确定</el-button>
        <el-button @click="renameVisible = false">取消</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="设置"
      :visible.sync="settingVisible"
      width="80%"
      center
      custom-class="dialog-setting">
      <Setting />
      <span slot="footer" class="dialog-footer">
        <el-button @click="settingVisible = false">取 消</el-button>
        <el-button type="primary" @click="settingVisible = false">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="导出"
      :visible.sync="exportVisible"
      width="480px"
      custom-class="dialog-export">
      <el-form label-width="80px" class="form-export">
        <el-form-item label="类型">
          <el-select v-model="formExport.type" placeholder="请选择类型">
            <el-option
              v-for="item in exportTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleExport">导出</el-button>
        <el-button @click="exportVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { objecter, filer, parser } from '@daelui/dogjs/dist/components.js'
import InterfaceView from './interface.vue'
import Setting from './setting/index.vue'
import FileGet from './data/file-get.vue'
import interfaceTpl from './constant/interface.js'
import utils from './data/utils.js'

// 接口集合
const collection = {
	info: {
		name: 'New Collection'
	},
	item: [
    objecter.clone(interfaceTpl)
  ]
}

export default {
  components: {
    InterfaceView,
    Setting,
    FileGet
  },

  props: {
    collection: {
      default () {
        return collection
      }
    },
    value: {
      default () {
        return collection.item[0]
      }
    }
  },

  computed: {
    paths () {
      let name = this.collection.info.name
      let list = [
        { text: name },
        { text: this.value.name }
      ]
      return list
    }
  },

  data () {
    return {
      tabs: [
        {text: '配置', value: 'first'},
        {text: '请求', value: 'second'},
        {text: '实例', value: 'third'}
      ],
      activeTab: 'first',
      envList: [
        { label: '测试环境', value: 'dev' },
        { label: '生产环境', value: 'prod' }
      ],
      form: {
        env: ''
      },
      // 重命名
      renameVisible: false,
      formRename: {
        name: ''
      },
      // 设置
      settingVisible: false,
      formSetting: {},
      // 导出
      exportVisible: false,
      formExport: {
        type: 'postman'
      },
      exportTypeList: [
        {label: 'Postman', value: 'postman'}
      ]
    }
  },

  methods: {
    // 显示重命名
    handleShowRename () {
      this.formRename.name = this.value.name
      this.renameVisible = true
    },
    // 确定重命名
    handleConfirmRename () {
      this.value.name = this.formRename.name
      this.renameVisible = false
    },
    // 显示设置
    handleShowSetting () {
      this.settingVisible = true
    },
    // 设置元数据
    setMetaData (inter) {
      inter = inter || {}
      let value = objecter.clone(interfaceTpl)
      value = Object.assign(value, inter)
      if (typeof value.request.url !== 'object') {
        value.request.url = {
          raw: value.request.url
        }
      }
      Object.assign(this.value, value)
    },
    // 获取元数据
    getMetaData () {
      let data = objecter.clone(this.value)
      data = utils.pureMeta(data)
      return data
    },
    // 导入
    handleImport (file) {
      filer.readFileText(file).then(text => {
        let data = parser.parse(text)
        if (data.info && data.item && data.item.length) {
          this.collection.info = data.info
          this.collection.item = data.item
          this.setMetaData(data.item[0])
        }
      })
    },
    // 显示导出窗口
    handleShowExport () {
      this.exportVisible = true
    },
    // 导出
    handleExport () {
      this.exportVisible = false
      let paths = this.paths
      paths = paths.map(item => item.text)
      if (!paths.length) {
        paths.push('New Interface')
      }
      let cname = paths[paths.length - 2] || paths[paths.length - 1]
      let metaData = this.getMetaData()
      if (this.formExport.type === 'postman') {
        this.exportPostmanData(cname, metaData)
      }
    },
    exportPostmanData (cname, metaData) {
      let data = this.getPostmanMetaData(cname, metaData)
      let fileName = cname + '.postman_collection.json'
      filer.downloadFile(fileName, JSON.stringify(data, null, '  '))
    },
    getPostmanMetaData (cname, data) {
      data = this.transformPostman(data)
      data = {
        info: {
          name: cname,
          schema: 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json'
        },
        item: [data]
      }
      return data
    },
    transformPostman (data) {
      let result = {}
      for (let key in data) {
        let value = data[key]
        if (Array.isArray(value)) {
          value.forEach(node => {
            if (node.hasOwnProperty('key') && node.hasOwnProperty('required')) {
              let b = node.required
              delete node.required
              if (b === false) {
                node.disabled = true
              }
            }
          })
          result[key] = value.map(node => {
            return this.transformPostman(node)
          })
        } else if (objecter.isPlainObject(value)) {
          result[key] = this.transformPostman(value)
        } else {
          result[key] = data[key]
        }
      }
      return result
    }
  }
}
</script>

<style lang="less" scoped>
.view-api {
  .view-head {
    display: flex;
    justify-content: space-between;
    align-items: center;
    min-height: 56px;
    padding: 8px 0;
    border-bottom: 1px solid #DCDFE6;
    .head-center {
      flex: 1;
    }
    .head-end {
      display: flex;
      align-items: center;
      /deep/.el-select {
        margin-left: 8px;
        width: 110px;
      }
      /deep/.el-button {
        margin-left: 8px;
      }
    }
  }
  .path-item {
    &:hover {
      color: #409EFF;
      .path-edit {
        display: inline;
      }
    }
    .path-edit {
      display: none;
      margin-left: 4px;
      cursor: pointer;
    }
  }

  .view-body {
    // margin-top: 8px;
  }
}
.form-export {
  /deep/.el-form-item:last-child {
    margin-bottom: 0;
  }
  /deep/.el-select {
    display: block;
  }
}
</style>

<style lang="less">
.d-bar-drawer {
  z-index: 99;
}
@media (max-width: 480px) {
  .dialog-export {
    width: 96vw !important;
  }
}
</style>